#include "UserManager.h"
#include "../room/AbstractRoom.h"

AbstractUser* UserManager::newUser(quint16 id, const QHostAddress& addr, quint16 port) {
    if (users.contains(id)) {
        return users[id];
    }

    AbstractUser* newUser = new AbstractUser(id, addr, port, nullptr, this);
    users[id] = newUser;
    return newUser;
}

void UserManager::removeUser(quint16 id) {
    if (users.contains(id)) {
        qDebug() << "Client disconnected:" << id;
        delete users[id];
        users.remove(id);
    } else {
        qDebug() << "Client not found:" << id;
    }
}

void UserManager::removeUser(const QHostAddress& addr, quint16 port) {
    for (auto it = users.begin(); it != users.end(); ++it) {
        if (it.value()->getAddress() == addr && it.value()->getPort() == port) {
            qDebug() << "Client disconnected:" << it.key();
            delete it.value();
            users.erase(it);
            return;
        }
    }
    qDebug() << "Client not found for addr/port";
}

void UserManager::UserBroadcast(quint16 id, const QByteArray& data) {
    AbstractRoom* room = findUser(id)->getRoom();
    if (room)
        room->broadcast(data, id);
}